package com.obrempon.credit.market.ui.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.view.View
import com.obrempon.credit.market.R
import com.obrempon.credit.market.base.app.ObremponActivityStackManager
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponPayStatusActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpAct
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 17:04
 * @Annotation：PIN 支付结果处理中
 */
class ObremponOrderPayStatusAct: HttpAct() {
    lateinit var binding: ObremponPayStatusActBinding
    //三方订单id
    private var thirdOrderId = ""

    //倒计时
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 30
    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        private const val INTENT_KEY_ORDER_ID = "thirdOrderId"
        fun start(context: Context, pName: String, pToken: String,orderId: String) {
            val intent = Intent(context, ObremponOrderPayStatusAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            intent.putExtra(INTENT_KEY_ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }

    override fun takeObremponRootView(): View {
        binding = ObremponPayStatusActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponBackBtnRes(R.mipmap.obrempon_back_white_icon)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        setObremponTextTitle(getString(R.string.obrempon_pay_status_title))
        setObremponTextTitleColor(getColor(R.color.white))
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))
        initObremponPaySatusRefreshView()
        binding.payStatusLayout.visibility = View.INVISIBLE
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Pin Payment Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Pin Payment Page")
        }
        //订单号复制
        binding.buttonPayOrderIdCopy.setOnClickListener {
            onOrderIdCopyAction(thirdOrderId)
        }
        //还款中 刷新
        binding.buttonUpdateStatus.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_PIN_PROCESS_PAYMENT_UPDATE,"TransactionId：${thirdOrderId}")
            loadObremponPayStatusAction()
        }
        //成功 - 再次申请
        binding.buttonApplyAgain.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_PIN_SUCCESS_APPLY_AGAIN,"TransactionId：${thirdOrderId}")
            showOrderPaySuccessAction()
        }
        //失败 - 重新发起支付
        binding.buttonMakeAgain2.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_PIN_FAILED_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
            onObremponPayAction()
        }
        //还款中 - 重新发起支付
        binding.buttonMakeAgain1.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_PIN_PROCESS_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
            onObremponPayAction()
        }
    }

    override fun takeObremponData() {
        loadObremponPayStatusAction()
    }

    /* 初始化刷新 */
    private fun initObremponPaySatusRefreshView() {
        binding.pinRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.pinRefreshView.setOnRefreshListener {
            loadObremponPayStatusAction()
        }
    }


    /**
     * 支付成功 - 跳转到可申请列表
     */
    private fun showOrderPaySuccessAction(){
        //刷新流程
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
        //返回首页
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SHOW_HOME))
        ObremponActivityStackManager.finishAllActivity(ObremponMainAct::class.java)
    }

    /**
     * 获取产品名称
     */
    private fun takeObremponProductName(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取产品Token
     */
    private fun takeObremponProductToken(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 三方订单id
     */
    private fun takeObremponPayThirdOrderId(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_ORDER_ID).toString()
    }

    /**
     * PIN 通用View
     */
    fun showObremponPayStatusCommonView(data: JSONObject) {
        binding.textPayAmount.text = data.optString("realRepayAmount","")
//        binding.textUnit.text = data.optString("")
        binding.textPayProduct.text = data.optString("product","")
        binding.textPayOrderId.text = data.optString("transactionId","")
        binding.payStatusLayout.visibility = View.VISIBLE
    }

    /**
     * PIN 支付成功
     */
    fun showObremponPayStatusSuccessView(data: JSONObject) {
        binding.imagePayStatus.setImageResource(R.mipmap.obrempon_pay_status_payment_success_icon)
        binding.textPayStatus.text = getString(R.string.obrempon_pay_status_payment_success)
        binding.textPayStatus.setTextColor(getColor(R.color.color_ff06cd69))

        binding.viewLine.visibility = View.VISIBLE
        binding.payOrderIdLayout.visibility = View.VISIBLE
        binding.buttonUpdateStatus.visibility = View.GONE
        binding.textPayReason.visibility = View.GONE
        binding.buttonMakeAgain1.visibility = View.GONE
        binding.buttonMakeAgain2.visibility = View.GONE
        binding.buttonApplyAgain.visibility = View.VISIBLE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付失败
     */
    fun showObremponPayStatusFailedView(data: JSONObject) {
        var showFailTitle = getString(R.string.obrempon_pay_status_failed_title)
        val failReason = data.optString("failReason","")
        binding.imagePayStatus.setImageResource(R.mipmap.obrempon_order_details_status_rejected_icon)
        if (failReason.isNotEmpty()){
            showFailTitle = "$showFailTitle\n($failReason)"
        }
        binding.textPayStatus.text = showFailTitle
        binding.textPayStatus.setTextColor(getColor(R.color.color_ffff4d14))

        binding.viewLine.visibility = View.VISIBLE
        binding.payOrderIdLayout.visibility = View.VISIBLE
        binding.buttonUpdateStatus.visibility = View.GONE
        binding.textPayReason.visibility = View.VISIBLE
        binding.textPayReason.text = getString(R.string.obrempon_pay_status_failed_reason)
        binding.buttonMakeAgain1.visibility = View.GONE
        binding.buttonMakeAgain2.visibility = View.VISIBLE
        binding.buttonApplyAgain.visibility = View.GONE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付中
     */
    fun showObremponPayStatusProcessView(data: JSONObject) {
        //是否是审核账号
        val isAdmin = ObremponSharedHelper.queryObremponSharedBoolean(ObremponSharedKey.OBREMPON_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接进入还款失败
            showObremponPayStatusFailedView(data)
            return
        }
        binding.imagePayStatus.setImageResource(R.mipmap.obrempon_credit_reviewing_icon)
        binding.textPayStatus.text = getString(R.string.obrempon_pay_status_processed)
        binding.textPayStatus.setTextColor(getColor(R.color.color_ff0569ff))

        binding.viewLine.visibility = View.GONE
        binding.payOrderIdLayout.visibility = View.GONE
        binding.buttonUpdateStatus.visibility = View.VISIBLE
        binding.textPayReason.visibility = View.VISIBLE
        binding.textPayReason.text = String.format(getString(R.string.obrempon_pay_status_processed_reason),data.optString("realRepayAmount",""))
        binding.buttonMakeAgain1.visibility = View.VISIBLE
        binding.buttonMakeAgain2.visibility = View.GONE
        binding.buttonApplyAgain.visibility = View.GONE

        countdown = 0
        showPinProcessStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startCountdownTimer()
        }
    }

    /**
     * 开启倒计时
     */
    private fun startCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 30

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: ObremponOrderPayStatusAct, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showPinProcessStatus()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.loadObremponPayStatusAction(false)
        }
    }

    /**
     * 设置按钮状态
     */
    private fun showPinProcessStatus(){
        if (countdown <= 0){
            binding.buttonMakeAgain1.isEnabled = true
            binding.buttonMakeAgain1.text = String.format(getString(R.string.obrempon_pay_status_make_payment_again),"")
        } else {
            binding.buttonMakeAgain1.isEnabled = false
            binding.buttonMakeAgain1.text = String.format(getString(R.string.obrempon_pay_status_make_payment_again),"(${countdown}s)")
        }
    }

    /**
     * 复制
     */
    private fun onOrderIdCopyAction(orderId: String){
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_PIN_ORDER_ID_COPY, "TransactionId：$orderId")
        // 获取剪贴板管理器
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", orderId)
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showObremponToast(getString(R.string.obrempon_customer_dialog_email_copy_success))
    }

    /**
     * 获取支付状态
     */
    private fun loadObremponPayStatusAction(isStartCountdown: Boolean = true){
        showObremponLoading()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_REPAYMENT_STATUS_PATH)
            put("product",takeObremponProductName())
            put("token",takeObremponProductToken())
            put("thirdOrderId",thirdOrderId)//三方订单id
        }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideObremponLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    obj.put("isStartCountdown",isStartCountdown)
                    if (obj.has("transactionId")){
                        thirdOrderId = obj.optString("transactionId")
                    }
                    showObremponPayStatusCommonView(obj)
                    // PROCESSING /SUCCEEDED /FAILED
                    val status = obj.optString("status")
                    when(status){
                        "FAILED" -> {
                            showObremponPayStatusFailedView(obj)
                        }
                        "SUCCEEDED" -> {
                            showObremponPayStatusSuccessView(obj)
                        }
                        else -> {
                            showObremponPayStatusProcessView(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 订单还款
     */
    private fun onObremponPayAction(){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("product",takeObremponProductName())
            put("token",takeObremponProductToken())
            put("mobile",ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_MOBILE))
            put("path",ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_REPAYMENT_MARKET_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                hideObremponLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null && obj.has("thirdOrderId")){
                    thirdOrderId = obj.optString("thirdOrderId")
                }
                loadObremponPayStatusAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.pinRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        thirdOrderId = takeObremponPayThirdOrderId()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOAN_PIN_REPAYMENT_START,"TransactionId：${thirdOrderId}")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOAN_PIN_REPAYMENT_END,"TransactionId：${thirdOrderId}")
    }
}